package com.torlesse.authdemo.aspect;

import com.alibaba.fastjson.JSONObject;
import com.torlesse.authdemo.common.annotation.RoleAuth;
import com.torlesse.authdemo.common.resp.Result;
import com.torlesse.authdemo.utlis.jwt.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: torlesse-liang
 * @Date: 2022/02/19/10:13
 * @Description:权限校验切面类
 */
@Aspect
@Component
public class AuthAspect {
    @Autowired
    private HttpServletRequest request;

    @SneakyThrows
    @Around("@annotation(com.torlesse.authdemo.common.annotation.RoleAuth)")
    public Object around(ProceedingJoinPoint joinPoint) {

        // 获取注解中的参数值
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        // 获取注解RoleAuth
        RoleAuth annotation = method.getAnnotation(RoleAuth.class);
        // 获取注解RoleAuth的value参数的值
        String role = annotation.value();
        String token = request.getHeader("Authorization");
        Claims claims = JwtUtil.parseJWT(token);
        if (claims == null) {
            return new Result(false, 20001, "token有误");
        }
        HashMap<String, Object> hashMap = JSONObject.parseObject(claims.getSubject(), HashMap.class);
        String roleInfo = (String) hashMap.get("role");
        if (roleInfo.contains(role)) {
            return joinPoint.proceed();
        } else {
            return new Result(false, 20001, "权限不足");
        }
    }
}
